#include "ucos_ii.h"
#include "bsp.h"

static  OS_STK App_StartTask1Stk[APP_START_OS_CFG_TASK_STK_SIZE]; 
static  OS_STK App_StartTask2Stk[APP_START_OS_CFG_TASK_STK_SIZE]; 

extern void  OSTimeTick(void);

void OS_CPU_ExceptHndlr(INT32U except_type)
{
    if (except_type == OS_CPU_ARM_EXCEPT_IRQ) 
    {
        if (BSP_IsTimer4Pending()) {
            OSTimeTick();
        }

        BSP_ClearIntPending();
    }
}

void OSTaskReturnHook(OS_TCB *ptcb)
{
    APP_TRACE_DEBUG(("Task returned.\n"));
}

static void App_Task1Start (void *p_arg) 
{
    INT8U n;

    (void)&p_arg;       /* Prevent compiler warning. */

    APP_TRACE_DEBUG(("Initialize OS timer...\n"));
    OSTmr_Init();         /* Initialize OS timer.*/

    n = 1;
    while (1) {
        APP_TRACE_DEBUG(("t1. Looping..\n"));
        OSTimeDly(10);
        if (n > 4) n = 1;

        LED_On(n);
        n++;
    }
}

static void App_Task2Start (void *p_arg) 
{
    (void)&p_arg;       /* Prevent compiler warning. */

    while (1) {
        APP_TRACE_DEBUG(("t2. Looping..\n"));
        OSTimeDly(5);
    }
}


void entry (void)
{
    INT8U os_err;

    (void)&os_err;  /* Warning: With some debuggers the first call is */ 
                    /* ignored. */
    OSInit();       /* Initialize OS. */

    os_err = 0;
    BSP_Init();     /* Initialize BSP. */
    BSP_InstallTimer4();
    CPU_Init();     /* Initialize CPU. */

    APP_TRACE_DEBUG(("Initialize OS...\n")); 

    /* Create start task. */
    OSTaskCreateExt( App_Task1Start, (void *)0, 
            (OS_STK *)&App_StartTask1Stk[APP_START_OS_CFG_TASK_STK_SIZE - 1], 
            APP_START_OS_CFG_TASK1_PRIO, 1, 
            (OS_STK *)&App_StartTask1Stk[0], APP_START_OS_CFG_TASK_STK_SIZE, 
            (void *)0, OS_TASK_OPT_STK_CHK | OS_TASK_OPT_STK_CLR);

    OSTaskCreateExt( App_Task2Start, (void *)0, 
            (OS_STK *)&App_StartTask2Stk[APP_START_OS_CFG_TASK_STK_SIZE - 1], 
            APP_START_OS_CFG_TASK2_PRIO, 2, 
            (OS_STK *)&App_StartTask2Stk[0], APP_START_OS_CFG_TASK_STK_SIZE, 
            (void *)0, OS_TASK_OPT_STK_CHK | OS_TASK_OPT_STK_CLR);

#if (OS_TASK_NAME_SIZE >= 16)
    OSTaskNameSet(OS_TASK_IDLE_PRIO, "Idle", &os_err);
  #if (OS_TASK_STAT_EN > 0)
    OSTaskNameSet(OS_TASK_STAT_PRIO, "Stat", &os_err);
  #endif
    OSTaskNameSet(APP_START_OS_CFG_TASK_PRIO, "Start", &os_err);
#endif
    APP_TRACE_DEBUG(("Start OS...\n")); 
    
    OSStart(); /* Start OS.*/
}
